package com.lib.utils;

import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.Application;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;

import java.io.FileInputStream;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <pre>
 *     author: Blankj
 *     blog  : http://blankj.com
 *     time  : 2016/10/18
 *     desc  : 进程相关工具类
 * </pre>
 */
public class ProcessUtils {

    private ProcessUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 获取前台应用包名
     * <p>当不是查看当前App，且SDK >= 22时，
     * 需添加权限 {@code <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>}</p>
     *
     * @param context 上下文
     * @return 前台应用包名
     */
    public static String getForegroundProcessName(Context context) {

        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
        if (infos != null && infos.size() != 0) {
            for (ActivityManager.RunningAppProcessInfo info : infos) {
                if (info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    return info.processName;
                }
            }
        }
        if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            System.out.println(list);
            if (list.size() > 0) {// 有"有权查看使用权限的应用"选项
                try {
                    ApplicationInfo info = packageManager.getApplicationInfo(context.getPackageName(), 0);
                    AppOpsManager aom = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
                    if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
                        context.startActivity(intent);
                    }
                    if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
                        XLog.i("没有打开\"有权查看使用权限的应用\"选项");
                        return null;
                    }
                    UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
                    long endTime = System.currentTimeMillis();
                    long beginTime = endTime - 86400000 * 7;
                    List<UsageStats> usageStatses = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, beginTime, endTime);
                    if (usageStatses == null || usageStatses.isEmpty())
                        return null;
                    UsageStats recentStats = null;
                    for (UsageStats usageStats : usageStatses) {
                        if (recentStats == null || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) {
                            recentStats = usageStats;
                        }
                    }
                    return recentStats == null ? null : recentStats.getPackageName();
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            } else {
                XLog.i("无\"有权查看使用权限的应用\"选项");
            }
        }
        return null;
    }

    /**
     * 清除后台进程
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>}</p>
     *
     * @param context 上下文
     * @return 清除后台进程数
     */
    public static int cleanAllBackgroundProcesses(Context context) {

        int count = 0;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> infos = am.getRunningAppProcesses();
        if (infos == null || infos.size() == 0) {
            return 0;
        }
        Set<ActivityManager.RunningAppProcessInfo> set = new HashSet<>();
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            infos.remove(info);
            set.add(info);
            ++count;
        }
        infos = am.getRunningAppProcesses();
        if (infos == null || infos.size() == 0) {
            return count;
        }
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            set.remove(info);
            --count;
        }
        System.out.println(set);
        return count;
    }

    /**
     * 清除后台进程
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>}</p>
     *
     * @param context     上下文
     * @param packageName 包名
     * @return {@code true}: 清除成功<br>{@code false}: 清除失败
     */
    public static boolean cleanBackgroundProcesses(Context context, String packageName) {

        if (TextUtils.isEmpty(packageName.trim())) {
            return false;
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> infos = am.getRunningAppProcesses();
        if (infos == null || infos.size() == 0) {
            return true;
        }
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (Arrays.asList(info.pkgList).contains(packageName)) {
                am.killBackgroundProcesses(packageName);
            }
        }
        infos = am.getRunningAppProcesses();
        if (infos == null || infos.size() == 0) {
            return true;
        }
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (Arrays.asList(info.pkgList).contains(packageName)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 返回当前的进程名
     */
    public static String getCurrentProcessName(Context context) {
        String curProcessName = null;

        try {
            curProcessName = getCurrentProcessNameByInvoke();
            XLog.i("curProcessName 1->" + curProcessName + "");
        } catch (Throwable ignored) {
        }
        if (TextUtils.isEmpty(curProcessName)) {
            try {
                curProcessName = getCurrentProcessNameByFile();
                XLog.i("curProcessName 2->" + curProcessName);
            } catch (Throwable ignored) {
            }
        }
        if (TextUtils.isEmpty(curProcessName)) {
            curProcessName = getCurrentProcessNameByRunningProcesses(context);
        }

        if (TextUtils.isEmpty(curProcessName)) {
            curProcessName = context.getPackageName();
        }
        return curProcessName;
    }

    private static String getCurrentProcessNameByRunningProcesses(Context context) {
        String curProcessName = null;
        int pid = android.os.Process.myPid();
        try {
            ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
                if (appProcess.pid == pid) {
                    curProcessName = appProcess.processName;
                    XLog.i("curProcessName 0->" + curProcessName);
                    break;
                }
            }
        } catch (Throwable ignored) {
        }
        return curProcessName;
    }

    private static String getCurrentProcessNameByInvoke() throws Throwable {
        String processName = null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            processName = Application.getProcessName();
        }
        if (TextUtils.isEmpty(processName)) {
            Class<?> clzActivityThread = Class.forName("android.app.ActivityThread");
            try {
                Method methodCurrentProcessName = clzActivityThread.getDeclaredMethod("currentProcessName");
                methodCurrentProcessName.setAccessible(true);

                processName = (String) methodCurrentProcessName.invoke(null);
            } catch (Throwable ignored) {
            }
            if (TextUtils.isEmpty(processName)) {
                Method methodGetProcessName = clzActivityThread.getDeclaredMethod("getProcessName");
                methodGetProcessName.setAccessible(true);

                Method methodCurrentActivityThread = clzActivityThread.getDeclaredMethod("currentActivityThread");
                methodCurrentActivityThread.setAccessible(true);
                Object activityThread = methodCurrentActivityThread.invoke(null);

                processName = (String) methodGetProcessName.invoke(activityThread);
            }
        }
        return processName;
    }

    private static String getCurrentProcessNameByFile() throws Throwable {
        String name = null;

        String fn = "/proc/self/cmdline";
        try (FileInputStream in = new FileInputStream(fn)) {

            byte[] buffer = new byte[256];
            int len = 0;
            int b;
            while ((b = in.read()) > 0 && len < buffer.length) {
                buffer[len++] = (byte) b;
            }
            if (len > 0) {
                name = new String(buffer, 0, len, "UTF-8");
            }
        }
        return name;
    }
}